from __future__ import print_function
import os.path
import random

X = [
        ['~','9','2','*','5','*','6','+','-','.','2','5','*',',','v'],
    ['^','~',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','@']
    ]

last = lambda x: x[len(x)-1]     #Returns the last element of the list
modulo = lambda a, b: b % a

def greater (x, y):
		if x<y: return y
		else: return x

def get_value(A, x, y):
        try:
                return ord(A[x][y])
        except IndexError:
                while len(A) < x:
                        A.append([0])
                for z in A:
                        while len(z)<y:
                                z.append(0)
                return 0, A
        
def set_value(A, x, y, v):
        while True:
                try:
                        A[x][y] = chr(v)
                except IndexError:
                        while len(A) < x:
                                A.append([0])
                        for z in A:
                                while len(z)<y:
                                        z.append(0)
                        return A

def read2array(file):
        #This is eight spaces in
        if not os.path.isfile(file): return 0
        A = []        #Array
        main = open(file, "r")
#        try: size = int(main.readline())
#        except: size = 60
		size = 0,0
        while not (last(A)==[]):
                A.append(list(main.readline()[0]))
                last(A).pop()
				size[0] = size[0] + 1
				size[1] = greater(size[1], len(last(A)))
        return A, size                

def bef(array, out=None, size=25,80):
        if out: out = open(out, 'w')
        A = array
        pointer = 0,0
        stringmode = False
        direction = 0,1
        s = []    #stack
        x = A[pointer[0]][pointer[1]]
        digits = ['0','1','2','3','4','5','6','7','8','9']
        counter = 1
        while (x != '@') & (counter < 100):
                if x=='"': stringmode = not stringmode
                elif stringmode: s.append(ord(x))    #Pushes the ASCII of x
                elif x=='+': s.append(s.pop() + s.pop())    #Pushes a+b
                elif x=='-': s.append(0-(s.pop() - s.pop()))    #Pushes 0-(a-b), or b-a
                elif x=='*': s.append(s.pop() * s.pop())    #Pushes a*b
                elif x=='/': s.append(1/(s.pop() / s.pop()))    #Pushes 1/(a/b), or b/a
                elif x=='%': s.append(modulo(s.pop(), s.pop()))    #Pushes b modulo a
                elif x=="'": s.append(s.pop() < s.pop())    #Pushes 1 if a<b, 0 otherwise

                elif x=='>': direction = 0,1    #Start moving right
                elif x=='<': direction = 0,-1    #Start moving left
                elif x=='^': direction = -1,0    #Start moving up
                elif x=='v': direction = 1,0    #Start moving down
                elif x=='V': direction = 1,0    #Start moving down

                elif x=='!': s.append(not s.pop())    #Logical not
                elif x=='_': direction = 0,(-1+2*int(not s.pop()))    #Complicated way to say 'Pop a value; move right if value=0, left otherwise'
                elif x=='|': direction = (-1+2*int(not s.pop())),0    #Complicated way to say 'Pop a value; move down if value=0, up otherwise'
                elif x==':': s.append(last(s))    #Duplicates the top value
                elif x=='\\':    #Swaps the top two values
                    a=s.pop()
                    b=s.pop()
                    s.append(a)
                    s.append(b)
                elif x=='$': s.pop()    #Pop a value
                elif x=='.': print(s.pop())    #Pop a value and print integer representation
                elif x==',': print(chr(s.pop()))    #Pop a value and print the ASCII representation
                elif x=='#': pointer = (pointer[0]+direction[0], pointer[1]+direction[1])    #Moves one in direction
                elif x=='&':    #Asks user for an integer and pushes
                    while True:
                        try: 
                            s.append(int(raw_input('Give me a character:')))    #If it's an integer, pushes the integer
                            break    #Breaks the loop
                        except ValueError: pass    #If an integer is not given, passes
                elif x=='~':       #Asks user for a character and pushes
                    while True:
                        try: 
                            s.append(ord(raw_input('Give me a character:')))    #If it's a character, pushes the character
                            break    #Breaks the loop
                        except ValueError: pass    #If a character is not given, passes
                elif x=='p':    #Sets (a,b) to the ASCII of c
                    y=s.pop()
                    z=s.pop()
                    v=s.pop()
                    A = set_value(A, y, z, v)
                elif x=='g':    #Pushes the ASCII of (a,b)
                    y=s.pop()
                    z=s.pop()
                    A = getvalue(A, z, y)
                elif bool(digits.count(x)): s.append(int(x))    #If it's an integer, append the integer form.
                elif x=='?':    #Sets a random cardinal direction
                    d = random.randint(1,4)
                    if d==1: direction =  0, 1
                    elif d==2: direction =  0,-1
                    elif d==3: direction = -1, 0
                    elif d==4: direction =  1, 0
                counter = counter + 1
                pointer = (pointer[0]+direction[0], pointer[1]+direction[1])    #Moves one in direction
				
                x = A[pointer[0]][pointer[1]]    #Sets x to the appropriate position

        if out:
			out.write('The stack has: ')
			out.write(s)
			out.write('\nThe pointer is at: ')
			out.write(pointer)
			out.write('\nThe code is now: ')
			out.write(A)
		else: print('The stack has: ')
			print(s)
			print('The pointer is at: ')
			print(pointer)
			print('The code is now:')
			print(A)
        if out: out.close()

if __name__ == "__main__":
    import sys
    bef(read2array(sys.argv[1]), sys.argv[1])
    
    




###Start secondary file - function defs###





from __future__ import print_function
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import cgi
import re
import hashlib
import pickle
#import unicodedata
#import os.path
import urllib



test = 'http://www.thinkgeek.com/brain/fortune.cgi'
sep = '-------------------------------------------'


def htmlparser(string):
   newstring=""
   htmler=0
   x = 0
   a=0
   while a < (len(string)-15):
       a+=1
       if (string[a]=='t')&(string[a+1]=='e')&(string[a+2]=='>'):#If it's '<blockqoute>'
          htmler += 1
          a += 3
       elif (string[a]=='<')&(string[a+1]=='/')&(string[a+2]=='b'):#If it's '</blockqoute>'
          htmler += 1
       if htmler==1:
          newstring=newstring + string[a] #Adds the other characters
   return newstring

def asc(m):
   return chr(int(m.group(1)))
def regexhtml(string):
#Just a string of regular expressions to remove most common HTML formatting parts
   string = re.sub(r"\\'", "'", string)
   string = re.sub(r"&#(\d{2,3});", asc, string)
   string = re.sub(r"&nbsp;", " ", string)
   string = re.sub(r"\\n", r"\n", string)
   string = re.sub(r"\<BR\>", r"\n", string)
   string = re.sub(r"&gt;", r">", string)
   string = re.sub(r"&lt;", r"<", string)
   string = re.sub(r"&quot;", r'"', string)
   string = re.sub(r"&amp;", r"&", string)
   m = re.search(r"&.+?;", string)
   if m:
      string = regexmore(string)
      
   m = re.search(r"&.+?;", string)
   if m:
      print(m.group())
   return string
def regexmore(string):
   string = re.sub(r"&cent;", chr(162), string)
   string = re.sub(r"&brvbar;", chr(166), string)
   string = re.sub(r"&copy;", chr(169), string)
   string = re.sub(r"&laquo;", chr(169), string)
   string = re.sub(r"&reg;", chr(174), string)
   string = re.sub(r"&macr;", chr(175), string)
   string = re.sub(r"&acute;", chr(180), string)
   string = re.sub(r"&raquo;", chr(187), string)
   string = re.sub(r"&frac14;", chr(188), string)
   string = re.sub(r"&frac12;", chr(189), string)
   string = re.sub(r"&frac34;", chr(190), string)
   string = re.sub(r"&Uuml;", chr(220), string)
   string = re.sub(r"&THORN;", chr(222), string)
   string = re.sub(r"&euml;", chr(235), string)
   string = re.sub(r"&eth;", chr(240), string)
   string = re.sub(r"&ouml;", chr(246), string)
   string = re.sub(r"&oslash;", chr(248), string)
   string = re.sub(r"&uuml;", chr(252), string)
   string = re.sub(r"&thorn;", chr(254), string)
   return string

def urltostring(url): #This is a fairly thin wrapper
   x = regexhtml(htmlparser(urllib.urlopen(url).read()))
   return x[1:(len(x)-1)]
def oldtonewurl(url):
   return url
def fortunes(total=0, url=test):
   counter = 0
   while counter < total:
      text = urltostring(url)
#      thing = "stories/" + md5(text)
#      if (os.path.isfile(thing) == bool(0)):
#          story = open(thing, "w")
#          story.writelines(str(unicodedata.normalize("NFKD", text).encode('ascii', "ignore")))
#          story.close()

##          story = open("main.txt", "a")
##          story.writelines(str(unicodedata.normalize("NFKD", text).encode('ascii', "ignore")) + "\n")
##          story.close()

#          main = open("fortunes.txt", "a", errors='replace')
#          main.write(text + '\n' + md5(text) + '\n' + sep + '\n')
#          main.close()
#      else:
#         print('Fortune '+str(counter)+' of '+str(total)+', with hash '+str(md5(text))+' has already been done.')
      counter+=1
def t(n=10):
   fortunes(total = n, url=test)
def md5(text):
   return hashlib.md5(pickle.dumps(text)).hexdigest()

def timer(num):
   import time
   start = time.clock()
   t(num)
   end = time.clock()
   diff = end-start
   print('It took '+str(diff)+' seconds(?) to collate '+str(num)+' fortunes.')

#def rem():
#   import os
#   import shutil
#   os.remove('fortunes.txt')
#   shutil.rmtree('stories')
#   os.mkdir('stories')




###Start main file - Appengine piece###




from functions import *

class Fortune(db.Model):
    hash = db.StringProperty()
    content = db.TextProperty()
    date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>')

        fortunes = db.GqlQuery("SELECT * FROM Fortune ORDER BY date DESC LIMIT 10")

        for fortune in fortunes:
	    self.response.out.write('Hash of <b>%s</b>:' %cgi.escape(fortune.hash))
            self.response.out.write('<blockquote>%s</blockquote>' %
                                    cgi.escape(fortune.content))

        # Write the submission form and the footer of the page
        self.response.out.write("""
              <form action="/sign" method="post">
                <div><textarea name="content" rows="1" cols="60"></textarea></div>
                <div><input type="submit" value="Sign Guestbook"></div>
              </form>
            </body>
          </html>""")

class Guestbook(webapp.RequestHandler):
    def post(self):
        fortune = Fortune()
	number = self.request.get('content')
	j = 1
	while j<number:
		a = urllib.urlopen(test).read()
		fortune.content = regexhtml(htmlparser(a))
		fortune.hash = md5(fortune.content)
		fortune.put()
		j = j+1
	self.redirect('/')

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/sign', Guestbook)],
                                     debug=True)

def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()

